package com.example.module_detail.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.bawei.common.entity.MovieVideoEntity
import com.example.common.vm.BaseViewModel
import com.example.module_detail.intent.DetailViewIntent
import com.example.module_detail.model.DetailRepository
import com.example.module_detail.model.MovieDetailPagingSource
import com.example.module_detail.state.DetailUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class DetailViewModel @Inject constructor(private val repository:DetailRepository):BaseViewModel<DetailViewIntent>() {

    private var _uiState = MutableStateFlow<DetailUiState>(DetailUiState.LoadEmpty)
    val uiState :StateFlow<DetailUiState> = _uiState.asStateFlow()




    override fun dispatchIntent(intent: DetailViewIntent) {
        when(intent){
            is DetailViewIntent.LoadAuthorInfo ->loadAuthorInfo(intent.userId)
            is DetailViewIntent.LoadMovieCommend ->loadMovieCommend(intent.dataType,intent.itemId)
        }
    }

    private fun loadAuthorInfo(userId:String){
        viewModelScope.launch(Dispatchers.IO){
            try {
               withContext(Dispatchers.Main) {
                   val (code,data,msg) = repository.getAuthorInfoById(userId)
                   if(code == 0){
                       _uiState.value = DetailUiState.LoadAuthorInfoSuccess(data)
                   }else{
                       _uiState.value = DetailUiState.LoadAuthorInfoFail("请求失败$msg")
                   }
               }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = DetailUiState.LoadAuthorInfoFail("请求异常"+e.message)
            }finally {
                cancel()
            }
        }
    }
    private fun loadMovieCommend(dataType:Int,itemId:String){
        viewModelScope.launch(Dispatchers.IO){
            try {
                withContext(Dispatchers.Main){
                    val (code,data,msg) = repository.getMovieCommendById(dataType,itemId)
                    if(code == 0){
                        _uiState.value = DetailUiState.LoadMovieCommendSuccess(data)
                    }else{
                        _uiState.value = DetailUiState.LoadMovieCommendFail("请求失败$msg")
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = DetailUiState.LoadMovieCommendFail("请求异常${e.message}")
            }finally {
                cancel()
            }


        }
    }
    /**
     * 获取推荐电影列表
     */
    fun loadRecommendVideo(): Flow<PagingData<MovieVideoEntity>> {
        return Pager(config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false), pagingSourceFactory = { MovieDetailPagingSource() }).flow.cachedIn(viewModelScope)
    }


    /**
     * 获取分类电影列表
     */
    fun loadMutilVideoById(typeId: Int): Flow<PagingData<MovieVideoEntity>> {
        return Pager(config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false), pagingSourceFactory = { MovieDetailPagingSource(typeId)}).flow.cachedIn(viewModelScope)
    }

}